package edu.iss.demo.service;

import java.util.List;

import javax.annotation.Resource;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import edu.iss.demo.exception.EmployeeNotFound;
import edu.iss.demo.model.Employee;
import edu.iss.demo.repository.EmployeeRepository;

@Service
public class EmployeeServiceImlp implements EmployeeService {

	@Resource
	EmployeeRepository employeeRepository;

	@PersistenceContext
    private EntityManager entityManager;
	
	@Override
	@Transactional
	public Employee create(Employee s) {
		Employee e = s;
		return employeeRepository.save(e);
	}

	@Override
	@Transactional(rollbackFor = EmployeeNotFound.class)
	public Employee delete(long id) throws EmployeeNotFound {
		Employee deletedEmployee= employeeRepository.findOne(id);
		
		 

		if (deletedEmployee== null)
			throw new EmployeeNotFound();

		deletedEmployee.setDeleteFlag(true);
		employeeRepository.save(deletedEmployee);
		return deletedEmployee;
	}

	@SuppressWarnings("unchecked")
	@Override
	@Transactional
	public List<Employee> findAll() {
		
		return entityManager.createQuery("SELECT e FROM Employee e WHERE e.deleteFlag =:false").setParameter("false", false).getResultList();
	}
	
	
	@SuppressWarnings("unchecked")
	@Override
	@Transactional
	public List<Employee> findManagerList() {
		
		return entityManager.createQuery("SELECT e FROM Employee e WHERE e.deleteFlag =:false AND e.role=:manager").setParameter("false", false).setParameter("manager", "Manager").getResultList();
	}
	
	

	@Override
	@Transactional(rollbackFor = EmployeeNotFound.class)
	public Employee update(Employee s) throws EmployeeNotFound {
		Employee updatedEmployee = employeeRepository.findOne(s.getEmployeeId());

		if (updatedEmployee == null)
			throw new EmployeeNotFound();

		updatedEmployee.setName(s.getName());
		updatedEmployee.setRole(s.getRole());
		updatedEmployee.setReportingTo(s.getReportingTo());
		updatedEmployee.setEmail(s.getEmail());
		updatedEmployee.setContactNo(s.getContactNo());
		updatedEmployee.setDepartmant(s.getDepartmant());
		updatedEmployee.setAnnualLeavesTaken(s.getAnnualLeavesTaken());
		updatedEmployee.setMedicalLeavesTaken(s.getMedicalLeavesTaken());

		employeeRepository.flush();
		return updatedEmployee;
	}

	@Override
	@Transactional
	public Employee findById(long id) {
		
		
		return (Employee) entityManager.createQuery("SELECT e FROM Employee e WHERE e.employeeId=:id AND e.deleteFlag=:false").setParameter("id", id).setParameter("false", false).getSingleResult();
		
		
	}
	
	

}
